package com.lq.controller.user;

import com.lq.constant.Contant;
import com.lq.entity.User;
import com.lq.exception.UserIsExistException;
import com.lq.service.UserService;
import com.lq.util.DateUtil;
import com.lq.util.IOUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@WebServlet("/user/update")
@MultipartConfig
public class UserUpdateServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        User user = userService.findUserById(Integer.parseInt(id));


        req.setAttribute("user", user);
        req.getRequestDispatcher("/WEB-INF/pages/user/update.jsp").forward(req, resp);
    }

    //修改用户的业务逻辑
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String id = req.getParameter("id");

        //获取文件部分
        //声明变量，我们定义在外面，这样对变量进行处理异常的时候也不至于作用域只在try中
        Part profile = null;
        InputStream input = null;
        try {
            //需要使用注解@MultipartConfig才能使用下面方法，才能获取图片的输入流
            profile = req.getPart("profile");
            input = profile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //判断一下，如果上传一个空文件，我们抛出异常
        if(profile == null || input == null) {
            throw new RuntimeException("必须上传头像");
        }

        //需要使用uuid处理文件名，保证命名唯一确定
        String fileName = UUID.randomUUID() + "_"+profile.getSubmittedFileName();

        //根据日期给文件夹创建目录
        //为了保存代码低耦合和简介，这里进行了工具类封装
        String format = DateUtil.getNowString();
        //这里我们遵循开发规范，不应该将用户图片放在项目中，所以我们另外设置了一个文件路径作为项目的外部资源
        String path = Contant.BASE_PATH + format + "/";


        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        //将页面上传的图片复制到指定路径下，
        IOUtil.copy(input, path + fileName);
        String profileUrl = path + fileName;

        //对用户进行封装，并传递给Service层
        User user = new User(username, password, profileUrl);
        user.setId(Integer.parseInt(id));


        userService.update(user);
        req.getRequestDispatcher("/user").forward(req, resp);
    }
}
